﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChatForum.Domain;
using ChatForum.Database;
using System.Data;

namespace ChatForum.DAL
{
    public class ChatForumRepository : IRepository
    {
        private readonly DatabaseBase database;

        public ChatForumRepository(DatabaseBase database)
        {
            if (database == null)
                throw new ArgumentNullException("database");
            this.database = database;
        }

        public void Delete<T>(Guid entityId) where T : EntityBase
        {
            database.ExecuteNonQuery(database.CreateCommand().Delete<T>(entityId));
        }

        public IEnumerable<T> GetAll<T>() where T : EntityBase
        {
            using (IDataReader reader = database.ExecuteReader(database.CreateCommand().SelectAll<T>()))
            {
                return reader.ReadAll<T>();
            }
        }

        public T GetById<T>(Guid entityId) where T : EntityBase
        {
			using (IDataReader reader = database.ExecuteReader(database.CreateCommand().SelectByID<T>(entityId)))
            {
                return reader.FirstOrDefault<T>();
            }
        }

        public Guid Insert<T>(T entity) where T : EntityBase
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            entity.ID = NewID();
            entity.ModifiedBy = entity.CreatedBy;
            return database.ExecuteNonQuery(database.CreateCommand().Insert<T>(entity)) == 1 ? entity.ID : Guid.Empty;
        }
        private Guid NewID()
        {
            Guid id = Guid.NewGuid();
            if (id == Guid.Empty)
                id = Guid.NewGuid();
            return id;
        }

        public bool Modify<T>(T entity) where T : EntityBase
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            return database.ExecuteNonQuery(database.CreateCommand().Modify<T>(entity)) == 1;
        }
    }
}
